import hashlib
import json
import logging
import re
from urllib.parse import urlencode

import jsonpath
import requests
from django.http import JsonResponse
import urllib
from datetime import datetime
from lapi_app.models.environment_model.environment import Environment
from lapi_app.models.testcase_model.testcase import Variable_local, Asserts, Testcase, Batch_list_result
from lapi_app.models.testcase_model.testcase_tree import Menu

logger = logging.getLogger('django')


def batch_list_request(request):
    assert_task_status = 1
    variable_task_status = 1
    result_list = []
    bodys = json.loads(request.body)
    data = bodys["content"]
    for i in range(len(data)):
        for j in range(len(data) - i - 1):
            if data[j]["step"] > data[j + 1]["step"]:
                data[j], data[j + 1] = data[j + 1], data[j]
    for m in data:
        cases = Testcase.objects.filter(id=m["id"])
        for case in cases:
            env = Environment.objects.get(id=case.t_environment_id)
            url = case.t_url
            req_url = env.e_address + url

            # url处理
            if "${" in req_url and "}" in req_url:
                key = re.findall(r"\${(.+?)}", req_url)
                for a in range(len(key)):
                    v_key = "${" + key[a] + "}"
                    value_variable = Variable_local.objects.filter(local_name=str(v_key))
                    if value_variable.count() > 0:
                        variable = value_variable[0].local_result
                        req_url = req_url.replace(v_key, variable)
                    else:
                        task_status = 0
                        return JsonResponse({
                            "code": 101,
                            "message": str(v_key) + "变量数据库未找到"
                        })
            logger.info("请求url=" + req_url)

            # headers处理
            if case.t_header == '':
                headers = case.t_header
            else:
                try:
                    head = json.dumps(case.t_header)
                    if "${" in head and "}" in head:
                        key = re.findall(r"\${(.+?)}", head)
                        for b in range(len(key)):
                            h_key = "${" + key[b] + "}"
                            value_variable = Variable_local.objects.filter(local_name=str(h_key))
                            if value_variable.count() > 0:
                                variable = value_variable[0].local_result
                                head = head.replace(h_key, variable)
                            else:
                                task_status = 0
                                return JsonResponse({
                                    "code": 101,
                                    "message": str(h_key) + "变量数据库未找到"
                                })
                    headers = json.loads(head)
                except Exception as e:
                    task_status = 0
                    return JsonResponse({
                        "code": 101,
                        "message": "header参数类型错误",
                        "system_log": e
                    })
            logger.info("请求头=" + str(headers))

            # body处理
            if case.t_body == '' or case.t_body == {}:
                payload = case.t_body
            else:
                try:
                    body = json.dumps(case.t_body)
                    if "${" in body and "}" in body:
                        key = re.findall(r"\${(.+?)}", body)
                        for b in range(len(key)):
                            b_key = "${" + key[b] + "}"
                            value_variable = Variable_local.objects.filter(local_name=str(b_key))
                            if value_variable.count() > 0:
                                variable = value_variable[0].local_result
                                body = body.replace(b_key, variable)
                            else:
                                task_status = 0
                                return JsonResponse({
                                    "code": 101,
                                    "message": str(b_key) + "变量数据库未找到"
                                })
                    payload = json.loads(body)
                except Exception as e:
                    task_status = 0
                    return JsonResponse({
                        "code": 101,
                        "message": "body参数类型错误",
                        "system_log": e
                    })
            logger.info("请求体=" + str(payload))

            if case.api_type == 1:
                # 普通接口
                pass
            elif case.api_type == 2:
                # 海外SDK(测试环境+预发布+生产环境)
                jwt_key = "2895d9ad485692b52c1ecef7d5f28300"  # 参数管理字段: pay_sign(100000151-纵剑仙界)
                new_payload = {}
                for key in sorted(payload.keys()):
                    if key != "clicks" and not payload[key]:
                        new_payload[key] = "{}"
                    else:
                        new_payload[key] = json.dumps(payload[key], separators=(',', ':'), ensure_ascii=False)
                pay_load = urllib.parse.unquote(urlencode(new_payload).replace("+", " "))
                pay_load = pay_load.replace("'", '"')
                md5_data = pay_load + "&" + jwt_key
                md = hashlib.md5()
                md.update(md5_data.encode("utf-8"))
                md_result = md.hexdigest()
                logger.info("md5的结果 =" + str(md_result))
                payload.update({"sign": md_result})
            elif case.api_type == 8:
                # 研发二验获取token
                jwt_key = "91e64e9a1b3e3208d86b91980affe013"  # 参数管理字段: pay_sign(100000151-纵剑仙界)
                new_payload = {}
                payload.update({"jh_sign": jwt_key})
                for key in sorted(payload.keys()):
                    if key != "clicks" and not payload[key]:
                        new_payload[key] = "{}"
                    else:
                        new_payload[key] = json.dumps(payload[key], separators=(',', ':'), ensure_ascii=False)
                pay_load = urllib.parse.unquote(urlencode(new_payload).replace("+", ""))
                pay_load = pay_load.replace('"', '')
                md5_data = pay_load
                md = hashlib.md5()
                md.update(md5_data.encode("utf-8"))
                md_result = md.hexdigest()
                logger.info("md5的结果 =" + str(md_result))
                payload.update({"sign": md_result})
            elif case.api_type == 9:
                # 国内SDK二验（生产环境）
                jwt_key = "aaeb852f-5625-41ff-9e5c-af460edd45e9"
                new_payload = {}
                for key in sorted(payload.keys()):
                    if key != "clicks" and not payload[key]:
                        new_payload[key] = "{}"
                    else:
                        new_payload[key] = json.dumps(payload[key], separators=(',', '='), ensure_ascii=False)
                pay_loads = urllib.parse.unquote(urlencode(new_payload).replace("+", ""))
                pay_loades = pay_loads.replace('"', '')
                md5_data = pay_loades + "&" + jwt_key
                md = hashlib.md5()
                md.update(md5_data.encode("utf-8"))
                md_result = md.hexdigest()
                logger.info("md5的结果 =" + str(md_result))
                # headers.update({"Authorization": md_result, "Client": client})
                payload.update({"sign": md_result})
            elif case.api_type == 4:
                # 国内SDK（生产环境）
                jwt_key = "e4301a29-b4e0-4783-9458-6e1ca9508c2f"
                client = "ewogICJhcHBpZCI6ICI1MjYyMCIsCiAgImlkZmQxIjogIjIwMjIwMTExOmIwZTM2OTEwYWNjZGQ4MzZjNGE2ODI0OGQ0ODUyZGI0IiwKICAiZW11bGF0b3IiOiAiMCIsCiAgIm9wIjogIuS4reWbveenu+WKqCIsCiAgImRldmljZW5hbWUiOiAiaVBob25lOV8xIiwKICAiY2xpZW50aWQiOiAiNEMzMDVBMjgtRERCNi00RkE1LUE2NkItN0UxQTRGREFGMEU3IiwKICAiYnJhbmQiOiAiQXBwbGUiLAogICJhcHB2ZXJzaW9uIjogIjQuNS4yIiwKICAiaWRmZCI6ICIyMDIyMDExMTpiMGUzNjkxMGFjY2RkODM2YzRhNjgyNDhkNDg1MmRiNCIsCiAgInN5c3RlbXZlcnNpb24iOiAiMTMuNiIsCiAgInVhIjogIk1vemlsbGEvNS4wIChpUGhvbmU7IENQVSBpUGhvbmUgT1MgMTNfNiBsaWtlIE1hYyBPUyBYKSBBcHBsZVdlYktpdC82MDUuMS4xNSAoS0hUTUwsIGxpa2UgR2Vja28pIE1vYmlsZS8xNUUxNDgiLAogICJwYWNrYWdlbmFtZSI6ICJjb20uc3N6ei4yMDIxIiwKICAib3MiOiAiMSIsCiAgInVkaWQiOiAiZTE3OGE4ZjA3ZmZkMjY4NjQ5YWQ4MjNjNWU2NWU3NjA4IiwKICAibmV0IjogIjAiLAogICJ3biI6ICIiLAogICJ0aW1lc3RhbXAiOiAiMTY2MzcyMjk4MyIsCiAgInNka3ZlcnNpb24iOiAiMS40LjYuMyIsCiAgImlkZnYiOiAiNTkzRjc1M0MtRkExNy00QjE1LUFGRDgtMzU4RTFGRjlDMUIzIiwKICAiaWRmZDIiOiAiMjAyMTEyMDc6NjQzNWQ0MGUyNDQ4NTNiNzQ2ODYyYzFiNDE4NTExNmQiLAogICJzY3JlZW5zaXplIjogIjY2N3wzNzUiLAogICJpZGZhIjogIjRDMzA1QTI4LUREQjYtNEZBNS1BNjZCLTdFMUE0RkRBRjBFNyIKfQ=="
                md5_data = json.dumps(payload) + client + jwt_key
                md = hashlib.md5()
                md.update(md5_data.encode("utf-8"))
                md_result = md.hexdigest()
                logger.info("md5的结果 =" + str(md_result))
                headers.update({"Authorization": md_result, "Client": client})
            elif case.api_type == 6:
                # 星辰谷（生产环境）element ui + python django + mysql
                jwt_key = "252f5af8-0b91-41e9-b0f4-6773cba89fb6"
                client = "eyJhcHBpZCI6NTQxNjAsImFkaWQiOm51bGwsIm9zIjoxLCJjaGFubmVsIjoiZGVmYXVsdCIsInRpbWVzdGFtcCI6IjE2NjM2NjA3MTciLCJwYWNrYWdlbmFtZSI6ImNvbS5qdW5oYWkuc3RhcnNnYW1lYm94IiwiYnJhbmQiOiJBcHBsZSIsImRldmljZW5hbWUiOiJpUGhvbmUgMTQgUHJvIiwic3lzdGVtdmVyc2lvbiI6IjE2LjAiLCJhcHB2ZXJzaW9uIjoiMS4yLjMiLCJzY3JlZW5zaXplIjoiODUyfDM5MyIsIm9wIjoiIiwibmV0IjoxLCJ3biI6IiIsInVhIjoiTW96aWxsYS81LjAgKGlQaG9uZTsgQ1BVIGlQaG9uZSBPUyAxNl8wIGxpa2UgTWFjIE9TIFgpIEFwcGxlV2ViS2l0LzYwNS4xLjE1IChLSFRNTCwgbGlrZSBHZWNrbykgTW9iaWxlLzE1RTE0OCIsImVtdWxhdG9yIjoxLCJjbGllbnRpZCI6IjM1MTRiZTkxMDUxZDY0MzI5YTYyYzBmN2M5YjQzN2Y3IiwiaWRmdiI6IkY1MDdDMjJFLUNBN0ItNDA5Ni04Q0JBLTkxNDFCNUMyRjUyNiIsImlkZmEiOiIwMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDAiLCJpZGZkIjoiIiwiaWRmZDEiOiIiLCJpZGZkMiI6IiIsImFuZHJvaWRpZCI6bnVsbCwiaW1laSI6IkY1MDdDMjJFLUNBN0ItNDA5Ni04Q0JBLTkxNDFCNUMyRjUyNiIsIm9haWQiOiIiLCJ2YWlkIjoiIiwiYWFpZCI6IiIsInVkaWQiOiI0NGFiZGM5YmNlMDM2OWZjNGU2YTI3YTIzZTY2YjM3MDIiLCJleHRyYSI6IiJ9"
                md5_data = json.dumps(payload) + client + jwt_key
                md = hashlib.md5()
                md.update(md5_data.encode("utf-8"))
                md_result = md.hexdigest()
                logger.info("md5的结果 =" + str(md_result))
                headers.update({"Authorization": md_result, "Client": client})
            elif case.api_type == 3:
                # 国内SDK(测试环境-android)
                jwt_key = "a058c845-5f17-4b17-859d-95c8d1e0e7e2"
                client = "ewogICJhcHBpZCI6IDUwNDM2LAogICJvcyI6ICIyIiwKICAic2RrdmVyc2lvbiI6ICIxLjEzLjAuMDgyOSIsCiAgImFkaWQiOiAiMCIsCiAgIm1pZGRsZXdhcmV2ZXJzaW9uIjogIjEuMTMuMC4wODI5IiwKICAiY2xpZW50aWQiOiAiZDYxOWUxZmE3ZWU2ZTBlYWFmMWRiNzg3ODBlYWU0NjciLAogICJ0aW1lc3RhbXAiOiAxNjYyMDk5NTk1LAogICJwYWNrYWdlbmFtZSI6ICJjb20uanVuaGFpLnl6anEiLAogICJicmFuZCI6ICJPUFBPIiwKICAiZGV2aWNlbmFtZSI6ICJPUFBPIENQSDE4MzUiLAogICJzeXN0ZW12ZXJzaW9uIjogIjEwIiwKICAiYXBwdmVyc2lvbiI6IDEsCiAgInNjcmVlbnNpemUiOiAiMTA4MHwyMDY4IiwKICAib3AiOiAiIiwKICAibmV0IjogMSwKICAid24iOiAiIiwKICAidWEiOiAiTW96aWxsYS81LjAgKExpbnV4OyBBbmRyb2lkIDEwOyBDUEgxODM1IEJ1aWxkL1FQMUEuMTkwNzExLjAyMDsgd3YpIEFwcGxlV2ViS2l0LzUzNy4zNiAoS0hUTUwsIGxpa2UgR2Vja28pIFZlcnNpb24vNC4wIENocm9tZS8xMDQuMC41MTEyLjk3IE1vYmlsZSBTYWZhcmkvNTM3LjM2IiwKICAiZW11bGF0b3IiOiAiMCIsCiAgImlkZnYiOiAiIiwKICAiYW5kcm9pZGlkIjogImFhY2RjMjkzZDNlOGQwNzQiLAogICJpbWVpIjogIiIsCiAgIm9haWQiOiAiOEY3RkU4NzA0RkYzNDk5MTlGMTI5NzE1MEQ4NDM2NTlhNDUyMjNmMWUwMjhmN2VkNDYzOTgyYzY1NjdiMjlmYSIsCiAgInZhaWQiOiAiIiwKICAiYWFpZCI6ICJENjQ5MEVCNjczQTc0OUMyOEE4NDM1QTQwODc3QTk5RmZjMzNkZDk1YjAzMzZiYjU2NzRkOGY4NDljNDVlNjUxIiwKICAidWRpZCI6ICI0MWZkMWYwOGZiMmUyN2IyZjRkNmYyNGViZDhjNjdmMDciLAogICJjcHVfbW9kZWwiOiAiIE1UNjc3MVYvVyIsCiAgImNwdV9hbW91bnQiOiAiOCIsCiAgInJvbV9zaXplIjogMTMxMDcyLAogICJyYW1fc2l6ZSI6IDYxNDQsCiAgImV4dHJhIjogIiIKfQ=="
                md5_data = json.dumps(payload) + client + jwt_key
                md = hashlib.md5()
                md.update(md5_data.encode("utf-8"))
                md_result = md.hexdigest()
                logger.info("md5的结果 =" + str(md_result))
                # headers.update({"Client": client})
                headers.update({"Authorization": md_result, "Client": client})
            elif case.api_type == 7:
                jwt_key = "aa2b7854-f4bd-46a4-a574-0e22a2fd8b46"
                client = "ewogICJhcHBpZCIgOiAiNTIzMjQiLAogICJpZGZkMSIgOiAiMjAyMjAxMTE6N2ZjNWQ4NzYyZThjNDBmMGMxMTk2YjE0ZDVmZjQ2YTMiLAogICJlbXVsYXRvciIgOiAiMCIsCiAgIm9wIiA6ICLkuK3lm73ogZTpgJoiLAogICJleHRyYSIgOiB7CiAgICAiYXNhX2luZm8iIDogImV3b2dJQ0poWkVsa0lpQTZJREV5TXpRMU5qYzRPVEFzQ2lBZ0ltdGxlWGR2Y21SSlpDSWdPaUF4TWpNeU16SXlNaXdLSUNBaVkyOXVkbVZ5YzJsdmJsUjVjR1VpSURvZ0lrUnZkMjVzYjJGa0lpd0tJQ0FpYjNKblNXUWlJRG9nTVRJek5EVTJOemc1TUN3S0lDQWlZMkZ0Y0dGcFoyNUpaQ0lnT2lBeE1qTTBOVFkzT0Rrd0xBb2dJQ0poWkVkeWIzVndTV1FpSURvZ01USXpORFUyTnpnNU1Dd0tJQ0FpWTI5MWJuUnllVTl5VW1WbmFXOXVJaUE2SUNKVlV5SXNDaUFnSW1GMGRISnBZblYwYVc5dUlpQTZJSFJ5ZFdVS2ZRPT0iCiAgfSwKICAiZGV2aWNlbmFtZSIgOiAiaVBob25lMTFfNiIsCiAgImNsaWVudGlkIiA6ICJBNzg4RDU1My1BQTMzLTRGQjgtQTNDQy1ENzk0M0Y0NTVGNUUiLAogICJicmFuZCIgOiAiQXBwbGUiLAogICJhcHB2ZXJzaW9uIiA6ICIxLjEiLAogICJpZGZkIiA6ICIyMDIyMDExMTo3ZmM1ZDg3NjJlOGM0MGYwYzExOTZiMTRkNWZmNDZhMyIsCiAgInN5c3RlbXZlcnNpb24iIDogIjE1LjUiLAogICJ1YSIgOiAiTW96aWxsYVwvNS4wIChpUGhvbmU7IENQVSBpUGhvbmUgT1MgMTVfNSBsaWtlIE1hYyBPUyBYKSBBcHBsZVdlYktpdFwvNjA1LjEuMTUgKEtIVE1MLCBsaWtlIEdlY2tvKSBNb2JpbGVcLzE1RTE0OCIsCiAgInBhY2thZ2VuYW1lIiA6ICJjb20uaWp1bmhhaS5zZGsuZ2xvYmFsLmlvcy5kZW1vIiwKICAib3MiIDogIjEiLAogICJ1ZGlkIiA6ICI2ZWQ1ZWU2NjE5YmQ0NzUyOTY5YWQ0YzRkNjIzN2EzMDYiLAogICJuZXQiIDogIjAiLAogICJ3biIgOiAiIiwKICAidGltZXN0YW1wIiA6ICIxNjcyMzc5Mzc4IiwKICAic2RrdmVyc2lvbiIgOiAiMS42LjAuMCIsCiAgImlkZnYiIDogIjAwRDQyMEFFLThBMjMtNDI5Ni1BNDA0LTAyNDQ3N0MxREFCNCIsCiAgImlkZmQyIiA6ICIyMDIxMTIwNzplOTBlNDg5NzU1ZDM2NmI3ODlmZjc2YzZmMTMwMzVmMyIsCiAgInNjcmVlbnNpemUiIDogIjg5Nnw0MTQiLAogICJpZGZhIiA6ICJBNzg4RDU1My1BQTMzLTRGQjgtQTNDQy1ENzk0M0Y0NTVGNUUiCn0="
                md5_data = json.dumps(payload) + client + jwt_key
                md = hashlib.md5()
                md.update(md5_data.encode("utf-8"))
                md_result = md.hexdigest()
                logger.info("md5的结果 =" + str(md_result))
                headers.update({"Authorization": md_result, "Client": client})
            elif case.api_type == 5:
                # 星辰谷（测试环境）
                jwt_key = "22e012b9-ce1f-4e3d-85ad-b10c802e8fa8"
                client = "eyJhcHBpZCI6NTI3NTIsImFkaWQiOiIwIiwib3MiOjIsImNoYW5uZWwiOiJkZWZhdWx0IiwidGltZXN0YW1wIjoiMTY2NjY4NDU3NCIsInBhY2thZ2VuYW1lIjoiY29tLmp1bmhhaS5zdGFyc2dhbWVib3giLCJicmFuZCI6InNkbTcxMCIsImRldmljZW5hbWUiOiJQQkRNMDAiLCJzeXN0ZW12ZXJzaW9uIjoiMTAiLCJhcHB2ZXJzaW9uIjoiMS4zLjEiLCJzZGt2ZXJzaW9uIjoiMS4wLjAiLCJzY3JlZW5zaXplIjoiNzgwfDM2MCIsIm9wIjoiIiwibmV0IjoxLCJ3biI6IiIsInVhIjoiTW96aWxsYS81LjAgKExpbnV4OyBBbmRyb2lkIDEwOyBQQkRNMDAgQnVpbGQvUUtRMS4xOTA5MTguMDAxOyB3dikgQXBwbGVXZWJLaXQvNTM3LjM2IChLSFRNTCwgbGlrZSBHZWNrbykgVmVyc2lvbi80LjAgQ2hyb21lLzc3LjAuMzg2NS45MiBNb2JpbGUgU2FmYXJpLzUzNy4zNiIsImVtdWxhdG9yIjowLCJjbGllbnRpZCI6ImU5MGQ1NWEwNmRiMWZjNzYyMmQ3YjQwNzI1NWNiNjYzIiwiaWRmdiI6bnVsbCwiaWRmYSI6IiIsImlkZmQiOiIiLCJpZGZkMSI6IiIsImlkZmQyIjoiIiwiYW5kcm9pZGlkIjoiZWFlMmNmNWJlNTI2NjEwOCIsImltZWkiOiJlN2ExYzJmNS1hOGMzLTQzOGQtOGVjNC0wMjhlYTc0NGFkZTYiLCJvYWlkIjoib294eCIsInZhaWQiOiIiLCJhYWlkIjoiIiwidWRpZCI6IjE1NmZmNDM2MGU2YzFhZjA4ZjM1ZWJmNjkxMzhjODk0OSIsImV4dHJhIjoiIn0=="
                md5_data = json.dumps(payload) + client + jwt_key
                md = hashlib.md5()
                md.update(md5_data.encode("utf-8"))
                md_result = md.hexdigest()
                logger.info("md5的结果 =" + str(md_result))
                headers.update({"Authorization": md_result, "Client": client})
                logger.info("请求头=" + str(headers))

            # 请求方法：1：get， 2：post， 3：put， 4：delete
            # 参数类型：1:form-data， 2:Json， 3:x-www-form-urlencoded， 4:None
            # method处理
            # params处理
            p = case.t_params
            params = {}
            if not p:
                for item in p:
                    if item['key'] == '' or item['value'] == '':
                        params = {}
                    else:
                        params[item['key']] = item['value']
            else:
                params = {}
            logger.info("请求参数=" + str(params))
            method = str(case.t_method)
            logger.info("请求方法 =" + method)
            body_type = str(case.t_type)
            logger.info("参数类型 =" + body_type)

            res = None
            # Get
            if method == "1":
                if body_type == "1":
                    res = requests.get(req_url, params=payload, headers=headers)
                    logger.info("响应结果 =" + res.text)
                if body_type == "2":
                    res = requests.get(req_url, json=payload, headers=headers)
                    logger.info("响应结果 =" + res.text)
                if body_type == "3":
                    res = requests.get(req_url, data=payload, headers=headers)
                    logger.info("响应结果 =" + res.text)
                if body_type == "4":
                    res = requests.get(req_url, params=params, headers=headers)
                    logger.info("响应结果 =" + res.text)

            # Post
            if method == "2":
                if body_type == "1":
                    res = requests.post(req_url, data=payload, headers=headers)
                    logger.info("响应结果 =" + res.text)
                if body_type == "2":
                    res = requests.post(req_url, json=payload, headers=headers)
                    logger.info("响应结果 =" + res.text)
                if body_type == "3":
                    res = requests.post(req_url, data=payload, headers=headers)
                    logger.info("响应结果 =" + res.text)
                if body_type == "4":
                    res = requests.post(req_url, data=payload, headers=headers)
                    logger.info("响应结果 =" + res.text)
            # Put
            if method == "3":
                if body_type == "1":
                    res = requests.put(req_url, data=payload, headers=headers)
                    logger.info("响应结果 =" + res.text)
                if body_type == "2":
                    res = requests.put(req_url, json=payload, headers=headers)
                    logger.info("响应结果 =" + res.text)
                if body_type == "3":
                    res = requests.put(req_url, data=payload, headers=headers)
                    logger.info("响应结果 =" + res.text)
                if body_type == "4":
                    res = requests.post(req_url, data=payload, headers=headers)
                    logger.info("响应结果 =" + res.text)

            # Delete
            if method == "4":
                if body_type == "1":
                    res = requests.delete(req_url, data=payload, headers=headers)
                    logger.info("响应结果 =" + res.text)
                if body_type == "2":
                    res = requests.delete(req_url, json=payload, headers=headers)
                    logger.info("响应结果 =" + res.text)
                if body_type == "3":
                    res = requests.delete(req_url, data=payload, headers=headers)
                    logger.info("响应结果 =" + res.text)
                if body_type == "4":
                    res = requests.delete(req_url, data=payload, headers=headers)
                    logger.info("响应结果 =" + res.text)

            if res is None or res == "":
                assert_res = res.text
            else:
                # assert处理
                result = []
                assert_dict = {}
                a_data = Asserts.objects.filter(assert_testcase_id=case.id)
                if a_data is not None:
                    for a in a_data:
                        assert_dict.update({
                            a.assert_key: a.assert_value
                        })
                else:
                    assert_status = {
                        "status": "无参数断言"
                    }
                    result.append(assert_status)
                if assert_dict:
                    for key, value in assert_dict.items():
                        if str(value) == str(jsonpath.jsonpath(res.json(), key)[0]):
                            assert_status = {
                                "status": True,
                                "assert_key": key,
                                "assert_value": str(value),
                            }
                        else:
                            assert_status = {
                                "status": False,
                                "assert_key": key,
                                "assert_value": str(value),
                            }
                        result.append(assert_status)
                logger.info(f"断言结果={result}")

                # variable提取处理
                extract_result = []
                extract = case.t_extract
                if not extract:
                    extract_result = []
                else:
                    for v in extract:
                        if v["variable_name"] == '' or v["variable_name"] == '':
                            extract_dict = {
                                "message": "无参数提取"
                            }
                            extract_result.append(extract_dict)
                        elif Variable_local.objects.filter(local_name=v["variable_name"]).count() >= 0:
                            # 提取变量
                            try:
                                res_result = json.loads(res.text)
                            except Exception as e:
                                logger.info(str(e))
                            v_data = v["variable_data"].split(".")
                            logger.info("提取内容 =" + str(v_data))
                            try:
                                for a in v_data:
                                    if "[" in a and "]" in a:
                                        variable_1 = a.split('[')[0]
                                        variable_2 = a.split('[')[1].split(']')[0]
                                        res_result = res_result[variable_1][variable_2]
                                    else:
                                        res_result = res_result[a]
                                extract_dict = {
                                    "variable_name": v["variable_name"],
                                    "variable_data": v["variable_data"],
                                    "variable_result": str(res_result),
                                    "message": "参数提取成功"
                                }
                                extract_result.append(extract_dict)
                            except Exception as e:
                                variable_task_status = 0
                                extract_dict = {
                                    "variable_name": v["variable_name"],
                                    "variable_data": v["variable_data"],
                                    "variable_result": "参数提取失败" + str(e)
                                }
                                extract_result.append(extract_dict)
                    for e in extract_result:
                        if Variable_local.objects.filter(local_name=e["variable_name"]).count() > 0:
                            Variable_local.objects.filter(local_name=e["variable_name"]). \
                                update(local_data=e["variable_data"], local_result=e["variable_result"])
                        elif Variable_local.objects.filter(local_name=e["variable_name"]).count() == 0:
                            Variable_local.objects.filter(local_name=e["variable_name"]). \
                                create(local_name=e["variable_name"], local_data=e["variable_data"],
                                       local_result=e["variable_result"],
                                       local_user_id=bodys["user_id"])
                    logger.info("参数提取结果 =" + str(extract_result))
                    logger.info("接口响应时间 =" + str(res.elapsed.total_seconds()) + 's')
        if assert_task_status == 0 or variable_task_status == 0:
            status = 0
        else:
            status = 1
        p_result = {
            "url": req_url,
            "body": payload,
            "response": json.loads(res.text),
            "method": int(method),
            "params": params,
            "assert_data": result,
            "status": status,
            "username": case.t_user.username,
            "testcase_id": case.id,
            "response_time": str(res.elapsed.total_seconds()) + '秒',
            "extract_result": extract_result
        }
        result_list.append(p_result)
        if Batch_list_result.objects.filter(p_testcase_id=m["id"]).count() == 0:
            Batch_list_result.objects.create(url=req_url, body=payload, response=res.text, params=params,
                                             assert_data=result, status=status,
                                             p_user_id=bodys["user_id"], method=method,
                                             p_testcase_id=m["id"], response_time=str(res.elapsed.total_seconds()),
                                             extract_result=extract_result
                                             )
        else:
            Batch_list_result.objects.filter(p_testcase_id=m["id"]).update_or_create(
                url=req_url, body=payload, response=res.text, params=params,
                assert_data=result, status=status,
                p_user_id=bodys["user_id"], method=method,
                response_time=str(res.elapsed.total_seconds()),
                extract_result=extract_result)

    return JsonResponse({
        "code": 200,
        "message": "接口流配置执行成功",
        "content": result_list
    })


def get_case(request):
    try:
        data = json.loads(request.body)
        id = data["testcase_id"]
        menus = Menu.objects.filter(id=id)

        for m in menus:
            case_id = m.testcase_id
            cases = Testcase.objects.filter(id=case_id)
            for case in cases:
                labels = Menu.objects.filter(pid=m.pid)
                for j in labels:
                    case_dict = {
                        "id": j.testcase_id,
                        "project": j.label,
                        "name": m.label,
                        "environment": case.t_environment.e_address,
                        "url": case.t_url,
                        "method": case.t_method,
                        "step": 0,
                        "update_time": datetime.strftime(case.update_time, "%Y-%m-%d %H:%M:%S"),
                        "create_time": datetime.strftime(case.create_time, "%Y-%m-%d %H:%M:%S"),
                        "username": case.t_user.username
                    }
        return JsonResponse({
            "code": 200,
            "message": "添加接口成功",
            "content": case_dict
        })
    except Exception as e:
        return JsonResponse({
            "code": 200,
            "message": "添加接口失败",
            "content": str(e)
        })
